package com.ljs.module.controller;

import com.ljs.module.entity.template.systemconfig.SystemConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 系统配置项控制器
 * Created by lijunsai on 2021/10/08
 */
@Controller
@RequestMapping("/system/config")
public class BuildConfigController {

    /**
     * 构建系统配置项后直接下载
     * @param response
     * @param systemConfig
     * @throws Exception
     */
    @PostMapping("/build/down")
    public void build(HttpServletResponse response, SystemConfig systemConfig) throws Exception {
        response.reset();
        byte[] bytes = systemConfig.build().getBytes("UTF-8");
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + systemConfig.getFileName() + ".js");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
    }

    /**
     * 构建系统配置项后自动注入到项目中
     * @return
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/build")
    public String buildConfig(@RequestBody SystemConfig systemConfig) throws IOException {
        return systemConfig.build();
    }
}
